<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { singerApplyAPI, singerApplyVO } from "@/services/singerApply";
import IconSearch from "@/assets/icons/IconSearch.vue";
import IconMore from "@/assets/icons/IconMore.vue";
import { debounce } from "lodash-es";
import { ElMessage, ElMessageBox } from "element-plus";

interface SingerApplyVOExtended extends singerApplyVO {
  isSinger?: number;
}

const userData = ref<SingerApplyVOExtended[]>([]);
const query = ref({
  uname: "",
});
const size = ref("15");
const options = [
  { value: "15", label: "15" },
  { value: "20", label: "20" },
  { value: "30", label: "30" },
  { value: "40", label: "40" },
  { value: "50", label: "50" },
];

const currentPage = ref(1);
const total = ref(0);
const loading = ref(false);

// Dialog controls
const showDetailDialog = ref(false);
const showAddDialog = ref(false);
const currentDetailData = ref<singerApplyVO | null>(null);
const formData = ref<singerApplyVO>({
  id: 0,
  uid: "",
  uname: "",
  email: "",
  phone: "",
  sex: "",
  birthday: new Date(),
  avatarUrl: "",
  description: "",
  status: "",
});

// 计算分页后的表格数据
const paginatedTableData = computed(() => {
  return userData.value;
});

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getData();
};

// 处理每页显示数量改变
const handleSizeChange = (val: string) => {
  size.value = val;
  currentPage.value = 1;
  getData();
};

const handleViewDetail = (row: any) => {
  currentDetailData.value = { ...row };
  showDetailDialog.value = true;
};

const handleEdit = (row: any) => {
  formData.value = { ...row };
  showAddDialog.value = true;
};

// 新增审批方法
const handleApprove = async (row: SingerApplyVOExtended) => {
  try {
    const result = await ElMessageBox.confirm(
      "请确认通过审批操作",
      "审批歌手申请",
      {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 根据用户选择设置isSinger值
    const isApproved = result === "confirm";
    const statusText = isApproved ? "通过" : "拒绝";

    // 准备更新数据
    const updateData = {
      ...row,
      isSinger: isApproved ? 1 : 0,
      status: isApproved ? "已通过" : "已拒绝",
    };

    // 调用API更新
    await singerApplyAPI().updateUser(updateData);
    ElMessage.success(`已${statusText}该歌手申请`);
    getData(); // 刷新数据
  } catch (error) {
    // 用户点击关闭按钮或取消操作时不处理
    if (error !== "cancel" && error !== "close") {
      console.error("审批操作失败:", error);
      ElMessage.error("操作失败");
    }
  }
};

const handleAdd = () => {
  formData.value = {
    id: 0,
    uid: "",
    uname: "",
    email: "",
    phone: "",
    sex: "",
    birthday: new Date(),
    avatarUrl: "",
    description: "",
    status: "",
  };
  showAddDialog.value = true;
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm("确定要删除该用户吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await singerApplyAPI().deleteUser(row);
    ElMessage.success("删除成功");
    getData();
  } catch (error) {
    console.error("删除失败:", error);
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const submitForm = async () => {
  try {
    if (formData.value.id) {
      await singerApplyAPI().updateUser(formData.value);
      ElMessage.success("更新成功");
    } else {
      await singerApplyAPI().addUser(formData.value);
      ElMessage.success("添加成功");
    }
    showAddDialog.value = false;
    getData();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 搜索方法
const handleSearch = debounce(() => {
  currentPage.value = 1;
  getData();
}, 500);

/** 初始化 **/
onMounted(() => {
  getData();
});

// 监听搜索条件变化
watch(
  () => query.value.uname,
  () => {
    handleSearch();
  }
);

const getData = async () => {
  try {
    loading.value = true;
    const response = await singerApplyAPI().getUser(query.value.uname);

    userData.value = response.data;
    total.value = response.data.total;
  } catch (error) {
    console.error("获取用户数据失败:", error);
    ElMessage.error("获取用户数据失败");
  } finally {
    loading.value = false;
  }
};

const handleReject = async (row: SingerApplyVOExtended) => {
  try {
    await ElMessageBox.confirm("确定要拒绝该歌手申请吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const updateData = {
      ...row,
      isSinger: 0,
      status: "已拒绝",
    };

    await singerApplyAPI().updateUser(updateData);
    ElMessage.success("已拒绝歌手申请");
    getData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("拒绝失败:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 格式化显示的函数
const formatField = (value: any, fieldName: string) => {
  if (value === null || value === undefined || value === "") {
    switch (fieldName) {
      case 'email':
      case 'phone':
        return '未填写';
      case 'sex':
        return '未填写';
      case 'status':
        return '未设置';
      case 'description':
        return '无';
      default:
        return value;
    }
  }
  return value;
};
</script>

<template>
  <div class="flex h-full gap-6">
    <div
      class="flex-1 bg-white rounded-lg p-4 flex flex-col justify-between min-w-0"
    >
      <div class="flex items-center justify-between gap-8 mb-4 flex-wrap">
        <div class="flex gap-8 flex-wrap">
          <div>
            <el-input
              v-model="query.uname"
              class="input-grey"
              style="width: 200px"
              placeholder="输入用户名搜索"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <IconSearch class="w-4 h-4 cursor-pointer" />
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="paginatedTableData"
        style="width: 100%"
        height="85%"
        header-row-class-name="table-header"
        cell-class-name="table-cell"
      >
        <el-table-column
          prop="uname"
          label="用户名"
          align="center"
          width="120"
        />
        <el-table-column label="性别" align="center" width="80">
          <template #default="{ row }">
            {{ formatField(row.sex, 'sex') }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱" align="center">
          <template #default="{ row }">
            {{ formatField(row.email, 'email') }}
          </template>
        </el-table-column>
        <el-table-column label="电话" align="center" width="150">
          <template #default="{ row }">
            {{ formatField(row.phone, 'phone') }}
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template #default="{ row }">
            {{ formatField(row.description, 'description') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240">
          <template #default="scope">
            <div class="flex justify-center gap-4">
              <el-button size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleApprove(scope.row)"
                :disabled="scope.row.isSinger === 1"
              >
                通过
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleReject(scope.row)"
                :disabled="scope.row.isSinger === 0"
              >
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-[36px] flex items-center justify-between mt-6">
        <div>
          <span class="text-[#8a8a8f] text-sm mr-2">每页结果</span>
          <el-select
            v-model="size"
            placeholder="Select"
            style="width: 70px"
            class="input-grey"
            @change="handleSizeChange"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-pagination
          background
          class="justify-items-end"
          layout="prev, pager, next"
          :total="total"
          :page-size="parseInt(size)"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 添加/编辑对话框 -->
  <el-dialog
    v-model="showAddDialog"
    :title="formData.id ? '编辑用户' : '添加用户'"
    width="50%"
  >
    <el-form :model="formData" label-width="100px">
      <el-form-item label="用户名" required>
        <el-input v-model="formData.uname" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="formData.phone" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="formData.sex" placeholder="请选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input
          v-model="formData.description"
          type="textarea"
          placeholder="请输入描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.icon {
  fill: currentColor;
  width: 20px;
  margin-right: 6px;
}
.input-grey {
  .el-input__wrapper {
    background: #f9f9f9;
    padding-left: 8px;
  }
  .el-select__wrapper {
    background: #f9f9f9;
  }
}
.el-table__header-wrapper {
  border-radius: 6px;
}
.table-header {
  background: #b88b7a !important;
  color: white;
  height: 50px !important;
  font-size: 15px;
  .el-table__cell {
    background: transparent !important;
    font-weight: 500;
  }
}
</style>